<template>
	<view class="bgbox po_rel">
		<un-navbar titleText="聊天" :isBack="false" :bgImgtype="1">
			<template #content>
				<image src="../../static/image/chat/adds.png" class=" addsclass po_abs" @click="addmask()">
				</image>
			</template>
		</un-navbar>
		<view id="scrollview">
			<scroll-view scroll-y="true" @scrolltolower="loadMore" class="wi_100 flex"
				:style="`height:${state.scrollviewheight}px`">
				<view class="flex1 flex flex_column" :style="`min-height:${state.scrollviewheight}px`">
					<view class="pa20">
						<view class="flex align_center search_box bg_white">
							<view class="iconfont i-fdj te_black9 ma_lr30"></view>
							<input class="flex1 f_s28" disabled @click="gochatsearch" placeholder="请输入关键词搜索" />
						</view>
					</view>
					<!-- <view class="ma_top40 ma_bottom30">
						<scroll-view scroll-x="true" class="wi_100 flex topscroll nowraps" scroll-with-animation>
							<view class="di_inbl ma_lr20">
								<view class="flex align_center flex_column">
									<view class="ov_hidden topuserimgbox flex align_center justify_center"
										:style="`background-image:url(${'https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'})`">

									</view>
									<view class="ma_top20 f_s26 topnames te_center ellipsis">设计指导2</view>
								</view>
							</view>

							<view class="di_inbl ma_lr20">
								<view class="flex align_center flex_column">
									<view class="ov_hidden topuserimgbox flex align_center justify_center"
										:style="`background-image:url(${'https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'})`">

									</view>
									<view class="ma_top20 f_s26 topnames te_center ellipsis">设计指导2</view>
								</view>
							</view>

							<view class="di_inbl ma_lr20">
								<view class="flex align_center flex_column">
									<view class="ov_hidden topuserimgbox flex align_center justify_center"
										:style="`background-image:url(${'https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'})`">

									</view>
									<view class="ma_top20 f_s26 topnames te_center ellipsis">设计指导2</view>
								</view>
							</view>

							<view class="di_inbl ma_lr20">
								<view class="flex align_center flex_column">
									<view class="ov_hidden topuserimgbox flex align_center justify_center"
										:style="`background-image:url(${'https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'})`">

									</view>
									<view class="ma_top20 f_s26 topnames te_center ellipsis">设计指导2</view>
								</view>
							</view>

							<view class="di_inbl ma_lr20">
								<view class="flex align_center flex_column">
									<view class="ov_hidden topuserimgbox flex align_center justify_center"
										:style="`background-image:url(${'https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'})`">

									</view>
									<view class="ma_top20 f_s26 topnames te_center ellipsis">设计指导2</view>
								</view>
							</view>

							<view class="di_inbl ma_lr20">
								<view class="flex align_center flex_column">
									<view class="ov_hidden topuserimgbox flex align_center justify_center"
										:style="`background-image:url(${'https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'})`">

									</view>
									<view class="ma_top20 f_s26 topnames te_center ellipsis">设计指导2</view>
								</view>
							</view>

							<view class="di_inbl ma_lr20">
								<view class="flex align_center flex_column">
									<view class="ov_hidden topuserimgbox flex align_center justify_center"
										:style="`background-image:url(${'https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'})`">

									</view>
									<view class="ma_top20 f_s26 topnames te_center ellipsis">设计指导2</view>
								</view>
							</view>

						</scroll-view>
					</view> -->

					<view class="flex1 bg_white chatlistbox">
						<uni-swipe-action v-for="(item,index) in store.state.conversationList" :key="item.targetId">
							<uni-swipe-action-item :right-options="state.options1"
								:show="state.isOpenedid==item.targetId?'right':'none'" :auto-close="false"
								@change="changeactionfun($event,item.targetId)"
								@click="changeactionfunClick(item,index)">
								<view class="chatlist pa_top30 pa_left30 flex" @click="gochat(item),item.unreadCount=0">

									<image class="ma_right30"
										:src="(store.state.friendinfo[item.targetId]?.avatar||'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png')+'?x-oss-process=image/resize,p_30'">
									</image>
									<view class="flex1 chatinfo he_100 pa_bottom30 ma_top4">
										<view class="flex justify_between align_center pa_right30">
											<view class="f_s34">
												{{store.state.friendinfo[item.targetId]?.remark_name||item.targetId}}
											</view>
											<view class="f_s26 te_blackccc">
												{{gettimes(item.operationTime)}}
											</view>
										</view>
										<view class="f_s26 te_black9 ma_top10 po_rel">
											<view class="ellipsis" style="width:200upx">
												{{item.lastMessage?.messageType==2?item.lastMessage?.text:item.lastMessage?.messageType==4?'图片消息':item.lastMessage?'名片消息':''}}
											</view>
											<view v-if="item.notificationLevel==5" class="iconfont i-mdrs tipsclass2 po_abs f_s32"></view>
											<view class="tipsclass po_abs" v-if="item.notificationLevel!=5&&item.unreadCount>0"></view>
										</view>

									</view>
								</view>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="modal bottom-modal pa_lr24" style="z-index: 1000;" :class="state.topshow?'show':''">
			<view class="dialog ma24 bg_white show_box bo_radius22 pa_tb30 ma_lr30 pa_lr30" @click.stop>
				<view class="pa_tb30 f_s32 line_bottom flex align_center" @click.stop="scanCode">
					<image src="../../static/image/chat/saoyisao.png" class="iconimgs ma_right10"></image>扫一扫
				</view>
				<view class="pa_tb30 f_s32 flex align_center" @click.stop="goaddfriends">
					<image src="../../static/image/chat/addhy.png" class="iconimgs ma_right10"></image>添加好友
				</view>
				<view class="cancel_btn te_cyan te_center bo_radius10" @click.stop="state.topshow = false">取消</view>
			</view>
		</view>

	</view>
</template>

<script setup lang="ts">
	import { showToast, getnavigationinfo, timestampToDate, getscrollviewheight, throttle } from '@/utils/utils'
	import { onLoad, onShow, onUnload, onReady } from '@dcloudio/uni-app'
	import { ref, reactive, getCurrentInstance } from 'vue'
	import { myget_user_info, friendcontact_user_avatar } from '@/api/chat'
	import { friend_is_friend } from "@/api/addressbook";
	import { useStore } from 'vuex'

	const instance = getCurrentInstance(); // 获取组件实例

	getnavigationinfo()

	const goaddfriends = () => {
		uni.navigateTo({
			url: '/subPackages/addressbook/addfriends/index'
		})
	}
	
	
	onShow(()=>{
		store.dispatch("init")
		friendcontact_user_avatar().then(res => {
			let friendinfo = res.data
			uni.setStorageSync('friendinfo', friendinfo)
			store.commit('setfriendinfo', friendinfo)
		
		
			console.log('好友信息好友信息好友信息好友信息好友信息好友信息好友信息', res.data)
		})
		
		myget_user_info().then(res => {
			let myinfo = res.data
			uni.setStorageSync('myinfo', myinfo)
			store.commit('setmyinfo', myinfo)
			console.log('我的信息我的信息我的信息我的信息我的信息我的信息我的信息', res.data)
		})
		
		
		let datass = {
			num:0,
			targetId:null,
			type:2
		}
		store.dispatch('getConversations', datass)
		
	})
	
	
	const scanCode = () => {
		uni.scanCode({
			success: function (res) {
				if (res.result.includes("jinbuff_")) {
					var system_code = res.result.replace('jinbuff_', '')
					friend_is_friend({
						system_code: system_code
					}).then((res) => {
						if (res.data.is_friend) {
							uni.navigateTo({
								url: '/subPackages/addressbook/userinfo/index?type=1&system_code=' + system_code
							})
						} else {
							uni.navigateTo({
								url: '/sssubPackages/addressbook/userinfo/index?unique_code=' + system_code
							})
						}
					}).catch((err) => {
						uni.showToast({
							title: err,
							icon: 'none'
						})
					})
				}
			}
		})
	}

	const gochatsearch = () => {
		uni.navigateTo({
			url: '/pages/chat/search'
		})
	}



	const gettimes = (timestamp) => {

		const targetDate = new Date(timestamp);
		const now = new Date();
		const yesterday = new Date(now);
		yesterday.setDate(now.getDate() - 1);

		// 获取目标时间的年月日时分
		const targetYear = targetDate.getFullYear();
		const targetMonth = targetDate.getMonth() + 1;
		const targetDay = targetDate.getDate();
		const targetHour = targetDate.getHours();
		const targetMinute = targetDate.getMinutes();

		// 格式化时分
		const formattedTime = `${targetHour < 10 ? '0' : ''}${targetHour}:${targetMinute < 10 ? '0' : ''}${targetMinute}`;

		// 判断是否是今天
		if (
			targetYear === now.getFullYear() &&
			targetMonth === now.getMonth() + 1 &&
			targetDay === now.getDate()
		) {
			return '今天' + formattedTime;
		}

		// 判断是否是昨天
		if (
			targetYear === yesterday.getFullYear() &&
			targetMonth === yesterday.getMonth() + 1 &&
			targetDay === yesterday.getDate()
		) {
			return '今天' + formattedTime;
		}

		// 判断是否是一周内
		const oneWeekAgo = new Date(now);
		oneWeekAgo.setDate(now.getDate() - 7);
		if (targetDate > oneWeekAgo) {
			const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
			const dayOfWeek = daysOfWeek[targetDate.getDay()];
			return `${dayOfWeek} ${formattedTime}`;
		}

		// 都不是，显示年月日
		return `${targetYear}-${targetMonth < 10 ? '0' : ''}${targetMonth}-${targetDay < 10 ? '0' : ''}${targetDay}`;



	}

	onReady(async () => {
		state.scrollviewheight = await getscrollviewheight('#scrollview', instance)
	})
	const store = useStore()





	// setInterval(()=>{
	// 	console.log(store.state.conversationList)	
	// },10000)



	const addmask = () => {
		state.topshow = true


	}

	const getlist = () => {
		let datas = {
			num: store.state.conversationList[store.state.conversationList.length - 1].operationTime,
			targetId: null,
			type:3
		}
		store.dispatch('getConversations', datas)
	}

	const loadMore = throttle(getlist, 1000)

	const price = ref<Number>()

	// if(uni.getStorageSync('friendinfo')){
	// 	friendcontact_user_avatar().then(res=>{
	// 		let friendinfo = res.data
	// 		uni.setStorageSync('friendinfo', friendinfo)
	// 		store.commit('setfriendinfo',friendinfo)


	// 		console.log('好友信息好友信息好友信息好友信息好友信息好友信息好友信息',res.data)
	// 	})
	// }


	const changeactionfun = (e, id) => { //滑动变化事件
		if (e === "right") { //滑动当前的，收回其他的删除按钮i
			state.isOpenedid = id
		}

	}

	const changeactionfunClick = async (item, index) => {

		let callback = {
			onConversationRemoved: (res) => {
				console.log('删除会话列表成功',res)
				
				
				store.commit('deleteconversationList',{index})
				
				// let datass = {
				// 	num:0,
				// 	targetId:null,
				// }
				// store.dispatch('getConversations', datass)
			}
		};
		let code = await store.state.engine.removeConversation(1, item.targetId, null, callback);
	}

	const gochat = async (e) => {

		// let datas = encodeURIComponent(JSON.stringify(e))

		// uni.navigateTo({
		// 	url: `/pages/chat/chat?result=${datas}`
		// })

		//targetId
		
		uni.navigateTo({
			url: `/pages/chat/chat?targetId=${e.targetId}`
		})

	}

	const state = reactive({
		isOpenedid: null,
		scrollviewheight: 0,
		topshow: false,
		list: [],
		options1: [{
			text: '删除',
			style: {
				backgroundColor: '#F95F48'
			}
		}],
	})
</script>
<style>

</style>

<style scoped lang="scss">
	$ztcolor: #39C7C1;

	.zttecolor {
		color: $ztcolor;
	}

	.ztbgcolor {
		background-color: $ztcolor;
	}


	.bgbox {
		width: 100vw;
		height: 100vh;
		//background: linear-gradient(180deg, #F0F4FE 0%, #FFFFFF 40%, #FFFFFF 100%);

		.addsclass {
			width: 40upx;
			height: 40upx;
			top: 0;
			right: 24upx;
			bottom: 0;
			margin: auto 0;
		}

		.search_box {
			height: 72upx;
			border-radius: 36upx;
		}

		.chatlistbox {
			border-radius: 60upx 60upx 0 0;

			.chatlist {
				image {
					width: 94upx;
					height: 94upx;
					border-radius: 30upx;
				}

				.chatinfo {
					border-bottom: 1upx solid #F6F6F6;

					.tipsclass {
						width: 20upx;
						height: 20upx;
						border-radius: 50%;
						background: #EC5A47;
						right: 30upx;
						bottom: 0;
					}
					.tipsclass2 {
						right: 30upx;
						bottom: 0;
					}
				}
			}
		}

		.topscroll {
			height: 150upx;

			.topscrollbox {
				width: 110upx;
			}

			.topuserimgbox {
				width: 94upx;
				height: 94upx;
				border-radius: 30upx;
				border: 4upx solid #3ABFCA;
				background-position: center center;
				background-size: cover;
				background-repeat: no-repeat;

			}

			.topnames {
				width: 110upx;
			}
		}

	}

	// 性别弹窗
	.show_box {
		width: 702upx;
	}

	.cancel_btn {
		width: 582upx;
		height: 88upx;
		line-height: 88upx;
		background: rgba(57, 199, 193, 0.15);
		margin: 30upx auto;
	}

	.line_bottom {
		border-bottom: 1px solid #F6F6F6;
	}

	.iconimgs {
		width: 40upx;
		height: 40upx;
		margin-left: 264upx;
	}

	
	.mdrclass{
		width: 6upx !important;
		height: 6upx !important;
	}
</style>